//
//  MeOrderViewController.m
//  CarUser
//
//  Created by 王森林 on 2019/1/23.
//  Copyright © 2019年 王森林. All rights reserved.
//

#import "MeOrderViewController.h"
#import "OrderCommonCell.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WXApi.h>
#import <WXApiObject.h>
@interface MeOrderViewController ()<WXApiDelegate>
@property (nonatomic, strong) NSMutableArray *userOrderAry;
@property (nonatomic, strong) NSMutableArray *indexAry;
@end

@implementation MeOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title  = @"订单";
    self.indexAry = [[NSMutableArray alloc] init];
    [self createUI];
    [self fetchDataFromNet];
    self.mainTableView.mj_header = [Custom_Mjfresh mj_customMjfreshHeaderSetting:^{
        [self fetchDataFromNet];
    }];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshData) name:NotificationCenterName_PaySuccess object:nil];
    // Do any additional setup after loading the view.
}
 - (void)refreshData
{
    
    //   用户订单
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    NSDictionary *orderParams = @{
                                  @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                                  @"TOKEN":user.TOKEN,
                                  @"USERNAME":user.mobile,
                                  @"NAME":user.USER.NICK00
                                  
                                  };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_26 params:orderParams md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        [self.mainTableView.mj_header endRefreshing];
        [self.userOrderAry removeAllObjects];
        NSDictionary *resultDict  = response;
        //        self.userOrderAry = [NSMutableArray arrayWithArray:[resultDict objectForKey:@"list"]];
        //        [self.mainTableView reloadData];
        
        NSArray *ary = [resultDict objectForKey:@"list"];
        if (ary != nil && ![ary isKindOfClass:[NSNull class]] && ary.count != 0)
        {
            [self hideNoDataView];
            self.userOrderAry = [NSMutableArray arrayWithArray:[resultDict objectForKey:@"list"]];
            
        } else {
            
            [self showNodataView:self.mainTableView.centerY-150 withView:self.mainTableView];
            
        }
        [self.mainTableView reloadData];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showInfoWithStatus:@"付款成功"];
        });
    
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
}


-(void)fetchDataFromNet
{
    //   用户订单
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    NSDictionary *orderParams = @{
                                  @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                                  @"TOKEN":user.TOKEN,
                                  @"USERNAME":user.mobile,
                                  @"NAME":user.USER.NICK00

                                  };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_26 params:orderParams md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
           [self.mainTableView.mj_header endRefreshing];
        [self.userOrderAry removeAllObjects];
        NSDictionary *resultDict  = response;
//        self.userOrderAry = [NSMutableArray arrayWithArray:[resultDict objectForKey:@"list"]];
//        [self.mainTableView reloadData];
        
        NSArray *ary = [resultDict objectForKey:@"list"];
        if (ary != nil && ![ary isKindOfClass:[NSNull class]] && ary.count != 0)
        {
            [self hideNoDataView];
            self.userOrderAry = [NSMutableArray arrayWithArray:[resultDict objectForKey:@"list"]];
            
        } else {
            
              [self showNodataView:self.mainTableView.centerY-150 withView:self.mainTableView];
            
        }
        [self.mainTableView reloadData];
        
     
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
               [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
}

- (void)createUI
{
    self.mainTableView.frame  = CGRectMake(0, 0, BOUNDWIDTH, BOUNDHEIGHT-(IS_IPHONE_X?88:64));
//    self.mainTableView.estimatedRowHeight = 290;
    [self.mainTableView registerClass:[OrderCommonCell class] forCellReuseIdentifier:@"OrderCommonCell"];
    
}


//微信支付
-  (void)getPayInfoWeixin:(NSString *)oderId
{
    
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"ORDERINFO_ID"],
                             @"TOKEN":user.TOKEN,
                             @"ORDERINFO_ID":oderId
                             
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_69 params:params md5Paraname:@"" success:^(id  _Nullable response) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
        NSDictionary *dict = [response objectForKey:@"result"];
        [WXApi registerApp:dict[@"appid"]];
        PayReq *request = [[PayReq alloc] init];
        request.partnerId = dict[@"mch_id"];
        request.prepayId= dict[@"prepay_id"];
        request.package = @"Sign=WXPay";
        request.nonceStr= dict[@"nonce_str"];
        request.timeStamp= (uint32_t)[dict[@"timestamp"] longValue];
        request.sign= dict[@"sign"];
        [WXApi sendReq:request];
        
        
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
}

- (void)pay:(NSString *)orderId
{
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"ORDERINFO_ID"],
                             @"TOKEN":user.TOKEN,
                             @"ORDERINFO_ID":orderId
                             
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_65 params:params md5Paraname:@"" success:^(id  _Nullable response) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
        NSDictionary *dict = response;
        
        [[AlipaySDK defaultService]payOrder:dict[@"body"] fromScheme:@"CarUser" callback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            NSString *result = resultDic[@"result"];
            BOOL isok = NO;
            if (result.length>0) {
                id resultDic = [result mj_JSONObject];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    if ([resultDic[@"alipay_trade_app_pay_response"][@"msg"] isEqualToString:@"Success"]) {
                        isok = YES;
                    }
                }
            }
            if ([resultDic[@"resultStatus"] integerValue] == 9000 && isok) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:@"付款成功"];
                    //                [SVProgressHUD dismissWithDelay:10];
                });
                //                [self.navigationController popViewControllerAnimated:YES];
                //                [[NSNotificationCenter defaultCenter] postNotificationName:BX_NotificationCenterName_AlipayPayBack object:nil userInfo:@{@"success":@"1",@"message":[NSString stringWithFormat:@"%@",resultDic[@"memo"]]}];
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:@"付款失败"];
                    //                [SVProgressHUD dismissWithDelay:10];
                });
                //                [[NSNotificationCenter defaultCenter] postNotificationName:BX_NotificationCenterName_AlipayPayBack object:nil userInfo:@{@"success":@"0",@"message":[NSString stringWithFormat:@"%@",resultDic[@"memo"]]}];
            }
        }];
        
        //        [dict objectForKey:@"body"];
        //        [self getPayInfo: [dict objectForKey:@"75f3fe547b4f4a3e9b56a73bccdc75d9"]];
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
}




#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1 ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.userOrderAry.count;
}
//#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([self.indexAry containsObject:indexPath]) {
        return 310;
    }
    return 280;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    switch (section) {
//        case 0:
//        {
//            return 0;
//        }
//            break;
//
//        default:
//        {
//            return 20.0f;
//        }
//            break;
//    }
//    return 0;
//}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BOUNDWIDTH, 20.0f)];
//    headView.backgroundColor = Common_Head_Color;
//    NSDictionary *secDict = self.totalCarAry[section-1];
//    UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, BOUNDWIDTH-15*2, 20.0f)];
//    dateLabel.text =  [secDict objectForKey:@"title"];
//    dateLabel.font = FONT_SIZE(12);
//    dateLabel.textColor = Common_HeadTitle_Color;
//    [headView addSubview:dateLabel];
//
//    return headView;
//
//}
//

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderCommonCell *cell = (OrderCommonCell *)[tableView dequeueReusableCellWithIdentifier:@"OrderCommonCell" forIndexPath:indexPath];
    cell.type = @"1";
    [cell setData:self.userOrderAry[indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.resultBlock = ^(id  _Nonnull response) {
    
        
        [UIActionSheet showInView:self.view withTitle:@"选择支付方式" cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"支付宝支付",@"微信支付"] tapBlock:^(UIActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
            NSLog(@"index%ld",buttonIndex);
            
          
            if (buttonIndex == 0) {
                [self pay:response];

            }
            if (buttonIndex == 1) {
                [self getPayInfoWeixin:response];

            }
            
            
        }];
//        [self pay:response];
        //        [UIActionSheet showInView:self.view withTitle:@"选择支付方式" cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"支付宝支付"] tapBlock:^(UIActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
        //            NSLog(@"index%ld",buttonIndex);
        //
        //            [self pay:response];
        //
        //
        //        }];
        
    };
    
    cell.expanBlock = ^(id  _Nonnull response) {
     
        if ([response isEqualToString:@"1"]) {
            [self.indexAry addObject:indexPath];
        } else {
            [self.indexAry removeObject:indexPath];
            
        }
        
           [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    };
    cell.cancleBlock = ^(id  _Nonnull response) {
        CustomAlertView *alert = [CustomAlertView alertViewWithTitle:@"取消订单" message:@"确定要取消订单吗?" btnTagClicked:^(NSInteger btnIndex) {
            
            if (btnIndex == 1) {
                
                UserRes *user = [CommonMethod getUser];
                if (!user) {
                    [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
                    return;
                }
                NSDictionary *params = @{
                                         @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                                         @"TOKEN":user.TOKEN,
                                         @"ORDERINFO_ID":response
                                         
                                         };
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showWithStatus:nil];
                });
                
                [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_29 params:params md5Paraname:nil success:^(id  _Nullable response) {
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                    });
                    [self fetchDataFromNet];
                    
                    
                    
                } fail:^(NSError * _Nonnull error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                    });
                    
                }];
            }
        }cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    };
    
    if ([self.indexAry containsObject:indexPath]) {
        cell.expanBtn.selected = YES;
    } else {
        cell.expanBtn.selected = NO;
    }
 
    //    [cell setData:self.topicAry[indexPath.row]];
    return cell;
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
